package cn.itcast.web.controller.cargo;

import cn.itcast.domain.cargo.*;
import cn.itcast.service.cargo.ContractProductService;
import cn.itcast.service.cargo.FactoryService;
import cn.itcast.web.controller.BaseController;
import cn.itcast.web.util.FileUploadUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;

@Controller
@RequestMapping("/cargo/contractProduct")
@Slf4j
public class ContractProductController extends BaseController {

    @Reference
    private ContractProductService contractProductService;
    @Reference
    private FactoryService factoryService;

    /**
     * 1. 列表
     */
    @RequestMapping("/list")
    public String list(String contractId,
                       @RequestParam(defaultValue = "1") Integer pageNum,
                       @RequestParam(defaultValue = "5") Integer pageSize) {
        log.info("执行货物列表查询开始...");
        // A. 根据购销合同id查询货物
        ContractProductExample example = new ContractProductExample();
        //SELECT * FROM co_contract_product WHERE contract_id=''
        example.createCriteria().andContractIdEqualTo(contractId);
        PageInfo<ContractProduct> pageInfo =
                contractProductService.findByPage(example, pageNum, pageSize);

        // B. 查询货物的厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);

         // C. 保存
        request.setAttribute("pageInfo", pageInfo);
        request.setAttribute("factoryList", factoryList);
        // 保存购销合同id，为了下一步点击保存货物时候拿到购销合同id
        request.setAttribute("contractId", contractId);
        return "cargo/product/product-list";
    }

    @Autowired
    private FileUploadUtil fileUploadUtil;
    /**
     * 2. 货物添加、修改
     * 货物图片：<input type="file" name="productPhoto" >
     */
    @RequestMapping("/edit")
    public String edit(ContractProduct contractproduct, MultipartFile productPhoto)  {
        contractproduct.setCompanyId(getLoginCompanyId());
        contractproduct.setCompanyName(getLoginCompanyName());
        if (StringUtils.isEmpty(contractproduct.getId())) {
            if (productPhoto != null) {
                try {
                    // 上传文件，获取上传文件的完整路径
                    String url = "http://"+fileUploadUtil.upload(productPhoto);
                    // 保存上传的图片路径
                    contractproduct.setProductImage(url);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            contractProductService.save(contractproduct);
        } else {
            contractProductService.update(contractproduct);
        }
        return "redirect:/cargo/contractProduct/list?contractId="+contractproduct.getContractId();
    }

    /**
     * 3.product-list.jsp点击修改，进入到product-update.jsp页面
     */
    @RequestMapping("/toUpdate")
    public String toUpdate(String id) {
        //1. 根据货物id查询
        ContractProduct contractProduct = contractProductService.findById(id);
        //2. 查询货物厂家
        FactoryExample factoryExample = new FactoryExample();
        factoryExample.createCriteria().andCtypeEqualTo("货物");
        List<Factory> factoryList = factoryService.findAll(factoryExample);
        //3. 保存
        request.setAttribute("contractProduct", contractProduct);
        request.setAttribute("factoryList", factoryList);
        return "cargo/product/product-update";
    }

    /**
     * 4. 货物删除
     * @param id   货物id，为了删除
     * @param contractId 购销合同id，为了跳转到货物列表（要传入购销合同id）
     * @return
     */
    @RequestMapping("/delete")
    public String delete(String id,String contractId) {
        contractProductService.delete(id);
        return "redirect:/cargo/contractProduct/list?contractId="+contractId;
    }

    /**
     * 5. 货物上传
     */
    @RequestMapping("/toImport")
    public String toImport(String contractId) {
        request.setAttribute("contractId",contractId);
        return "cargo/product/product-import";
    }


    /**
     * 5. 货物上传 - 选择文件上传
     * ApachePOI 导入
     */
    @RequestMapping("/import")
    public String importExport(String contractId,MultipartFile file) throws Exception {
        //1. 创建工作簿
        Workbook workbook = new XSSFWorkbook(file.getInputStream());
        //2. 获取工作表
        Sheet sheet = workbook.getSheetAt(0);
        //3. 获取总行数
        int rows = sheet.getPhysicalNumberOfRows();
        //4. 遍历行，从第二行开始遍历
        for (int i = 1; i < rows; i++) {
            //4.1 获取行对象
            Row row = sheet.getRow(i);

            //4.2 创建货物对象并封装
            ContractProduct contractProduct = new ContractProduct();
            contractProduct.setFactoryName(row.getCell(1).getStringCellValue());
            contractProduct.setProductNo(row.getCell(2).getStringCellValue());
            contractProduct.setCnumber((int) row.getCell(3).getNumericCellValue());
            contractProduct.setPackingUnit(row.getCell(4).getStringCellValue());
            contractProduct.setLoadingRate(row.getCell(5).getNumericCellValue()+"");
            contractProduct.setBoxNum((int) row.getCell(6).getNumericCellValue());
            contractProduct.setPrice(row.getCell(7).getNumericCellValue());
            contractProduct.setProductDesc(row.getCell(8).getStringCellValue());
            contractProduct.setProductRequest(row.getCell(9).getStringCellValue());
            // 【设置购销合同id】
            contractProduct.setContractId(contractId);
            // 【设置厂家id】
            Factory factory = factoryService.findByName(contractProduct.getFactoryName());
            if (factory != null) {
                contractProduct.setFactoryId(factory.getId());
            }

            //4.3 给购销合同添加货物
            contractProductService.save(contractProduct);
        }

        // 货物上传成功，跳转到购销合同列表
        return "redirect:/cargo/contract/list";
    }
}













